package com.lc.question.controller;

import com.lc.question.constant.MyConstants;
import com.lc.question.pojo.*;
import com.lc.question.service.impl.*;
import com.lc.question.pojo.*;
import com.lc.question.service.impl.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.util.*;

@Controller
@Api(tags = "planContrller|任务接口类")
@RequestMapping("/plan")
public class PlanController {

    @Autowired
    PlanServiceImpl planService;
    @Autowired
    StudentServiceImpl studentService;
    @Autowired
    TeacherServiceImpl teacherService;
    @Autowired
    UserTabServiceImpl userTabService;
    @Autowired
    QuestionServiceImpl questionService;
    @Autowired
    QuestionNaireServiceImpl questionNaireService;


    @PostMapping("/all")
    @ApiOperation(value = "根据发布人ID获取所有相关任务")
    @ApiImplicitParam(paramType = "query",name = "pub_Id",value = "发布人ID",required = true,dataType = "String")
    @ResponseBody //查询有关发布人所有任务
    public List<Plan> planAll(String pub_Id) {
        Plan plan = new Plan();
        plan.setPub_Id(pub_Id);
        return planService.planAll(plan);
    }

    @PostMapping("/plan_pub")
    @ApiOperation(value = "查询有关发布人的所有任务-条件查询")
    @ResponseBody //查询有关发布人的所有任务
    public List<Plan> findPlanByAnything(@RequestBody Plan plan) {
        return planService.findPlanByAnything(plan);
    }

    /**
     *
     * @param plan
     * @param currentPage 当前页
     * @param total 一页的总条数
     * @return
     */
    @PostMapping("/plan_COTime")
    @ApiOperation(value = "查询有关发布人的所有任务--根据创建时间顺序排序--分页")
    @ResponseBody //查询有关发布人的所有任务--根据创建时间顺序排序
    public PageBean<Plan> findPlanBy_COTime(@RequestBody Plan plan, @RequestParam("currentPage") int currentPage, @RequestParam("total") int total) {
        long totalNumber = planService.planTotal(plan);//总条数
        PageBean<Plan> planPageBean = new PageBean<Plan>(currentPage,total,totalNumber);
        int startIndex = planPageBean.getStartIndex();
        List<Plan> plans = planService.findPlan_COTime(plan, startIndex, total);
        planPageBean.setPageDate(plans);
        return planPageBean;
    }


    @PostMapping("/plan_CROTime")
    @ApiOperation(value = "查询有关发布人的所有任务--根据创建时间逆序排序--分页")
    @ResponseBody //查询有关发布人的所有任务--根据创建时间逆序排序
    public PageBean<Plan> findPlanBy_CROTime(@RequestBody Plan plan, @RequestParam("currentPage") int currentPage,@RequestParam("total") int total) {
        long totalNumber = planService.planTotal(plan);//总条数
        PageBean<Plan> planPageBean = new PageBean<Plan>(currentPage,total,totalNumber);
        int startIndex = planPageBean.getStartIndex();
        List<Plan> plans = planService.findPlan_CROTime(plan, startIndex, total);
        planPageBean.setPageDate(plans);
        return planPageBean;
    }

    @PostMapping("/plan_OROTime")
    @ApiOperation(value = "查询有关发布人的所有任务--根据结束时间顺序排序--分页")
    @ResponseBody //查询有关发布人的所有任务--根据结束时间顺序排序
    public PageBean<Plan> findPlanBy_OROTime(@RequestBody Plan plan, @RequestParam("currentPage") int currentPage,@RequestParam("total") int total) {
        long totalNumber = planService.planTotal(plan);//总条数
        PageBean<Plan> planPageBean = new PageBean<Plan>(currentPage,total,totalNumber);
        int startIndex = planPageBean.getStartIndex();
        List<Plan> plans = planService.findPlan_OROTime(plan, startIndex, total);
        planPageBean.setPageDate(plans);
        return planPageBean;
    }
    @PostMapping("/plan_OOTime")
    @ApiOperation(value = "查询有关发布人的所有任务--根据结束时间逆序排序--分页")
    @ResponseBody //查询有关发布人的所有任务--根据结束时间逆序排序
    public PageBean<Plan> findPlanBy_OOTime(@RequestBody Plan plan, @RequestParam("currentPage") int currentPage,@RequestParam("total") int total) {
        long totalNumber = planService.planTotal(plan);//总条数
        PageBean<Plan> planPageBean = new PageBean<Plan>(currentPage,total,totalNumber);
        int startIndex = planPageBean.getStartIndex();
        List<Plan> plans = planService.findPlan_OOTime(plan, startIndex, total);
        planPageBean.setPageDate(plans);
        return planPageBean;
    }

    @PostMapping("/planByName")
    @ApiOperation(value = "查询有关发布人的任务--通过plan_name模糊查询")
    @ResponseBody //查询有关发布人的任务--通过plan_name模糊查询
    public List<Plan> findPlanByName(@RequestBody Plan plan) {
        List<Plan> planByName = planService.findPlanByName(plan);
        return planByName;
    }

    @PostMapping("/update") //更改任务
    @ApiOperation(value = "update(更改任务)")
    public void updatePlan(@RequestBody Plan plan) {
        String obj_user = plan.getObj_user();
        int plan_id = plan.getPlan_Id();
        Date create_time = plan.getCreate_time();
        Date over_time = plan.getOver_time();
        String t_text = plan.getT_text();
        Plan plan2 = planService.findPlanByPid(plan_id);
        if (plan2.getObj_user().equals(obj_user)){
            planService.updatePlan(plan);
        }else{
            List<Student> students = studentService.studentList();
            List<Teacher> teachers = teacherService.teacherList();
            if (MyConstants.OBJ_STU.equals(obj_user)) {
                for (Student student : students) {//删除学生与计划的联系
                    String stu_id = student.getStu_Id();
                    userTabService.deleteUserTab2(plan_id,stu_id);
                }
                for (Teacher teacher : teachers) {//添加教职工与计划的联系
                    String tea_id = teacher.getTea_Id();
                    UserTab userTab = new UserTab(
                            tea_id,plan_id,MyConstants.SUR_UNFINISHED,MyConstants.PAR_UNFINISHED,
                            create_time,over_time,t_text
                    );
                    userTabService.addUserTab(userTab);
                }
            }else if(MyConstants.OBJ_TEA.equals(obj_user)){
                for (Teacher teacher : teachers) {//删除教职工与表的联系
                    String tea_id = teacher.getTea_Id();
                    userTabService.deleteUserTab2(plan_id,tea_id);
                }
                for (Student student : students) {//添加学生与表的联系
                    String stu_id = student.getStu_Id();
                    UserTab userTab = new UserTab(
                            stu_id,plan_id,MyConstants.SUR_UNFINISHED,MyConstants.PAR_UNFINISHED,
                            create_time,over_time,t_text
                    );
                    userTabService.addUserTab(userTab);
                }
            }

        }
    }

    @PostMapping("/add") //新增任务
    @ApiOperation(value = "add(新增任务)")
    public void addPlan(@RequestBody Plan plan) {
        planService.addPlan(plan);
        String obj_user = plan.getObj_user();
        int tab_id = plan.getTab_Id();
        Date create_time = plan.getCreate_time();
        Date over_time = plan.getOver_time();
        String t_text = plan.getT_text();
        if (MyConstants.OBJ_STU.equals(obj_user)) { //调查对象为学生时
            List<Student> students = studentService.studentList();
            for (Student student : students) {
                String stu_id = student.getStu_Id();
                UserTab userTab = new UserTab(
                        stu_id,tab_id,MyConstants.SUR_UNFINISHED,MyConstants.PAR_UNFINISHED,
                        create_time,over_time,t_text
                );
                userTabService.addUserTab(userTab);
            }
        } else if (MyConstants.OBJ_STU.equals(obj_user)) {//调查对象为教师时
            List<Teacher> teachers = teacherService.teacherList();
            for (Teacher teacher : teachers) {
                String tea_id = teacher.getTea_Id();
                UserTab userTab = new UserTab(
                        tea_id,tab_id,MyConstants.SUR_UNFINISHED,MyConstants.PAR_UNFINISHED,
                        create_time,over_time,t_text
                );
                userTabService.addUserTab(userTab);
            }
        }
    }

    @PostMapping("/delete") //删除任务
    @ApiOperation(value = "delete(删除任务)")
    public void deletePlan(Plan plan) {
        int plan_id = plan.getPlan_Id();
        String obj_user = plan.getObj_user();
        int tab_id = plan.getTab_Id();
        if (MyConstants.OBJ_STU.equals(obj_user)){
            List<Student> students = studentService.studentList();
            for (Student student : students) {
                String stu_id = student.getStu_Id();
                questionService.deleteQuestion2(tab_id,stu_id);
                userTabService.deleteUserTab2(tab_id,stu_id);
            }
        }else if(MyConstants.OBJ_TEA.equals(obj_user)){
            List<Teacher> teachers = teacherService.teacherList();
            for (Teacher teacher : teachers) {
                String tea_id = teacher.getTea_Id();
                questionService.deleteQuestion2(tab_id,tea_id);
                userTabService.deleteUserTab2(tab_id,tea_id);
            }
        }
        planService.deletePlan(plan_id);
    }

    @PostMapping("/judge") //判断是否有存在的任务
    @ApiOperation(value = "judge(判断是否有存在的任务)")
    @ResponseBody
    public boolean judgePlan(int tab_Id) {
        List<Plan> plans = planService.findPlanByTid(tab_Id);
        int flag = 0;
        for (Plan plan : plans) {
            flag = (plan==null || plan.getPlan_state().equals("FINISHED") || plan.getPlan_state().equals("HAVE_CANCELED")) ? flag : flag++;
        }
        if (flag==0){
            return true;//说明不存在尚未结束的有关该问卷的任务
        }else{
            return false;
        }
    }

    @PostMapping("/excel_tea") //教职工调研结果导出
    @ApiOperation(value = "excel_tea(判断是否有存在的任务)")
    @ResponseBody
    public boolean excel_Tea(int plan_id,String path) {
//        String path = "D:\\learn\\work\\com.zhp\\question\\";
        try {
            excelData_stu(plan_id,path);
            excelData_tea(plan_id,path);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @PostMapping("/excel_stu") //教职工调研结果导出
    @ApiOperation(value = "excel_stu(判断是否有存在的任务)")
    @ResponseBody
    public boolean excel_Stu(int plan_id,String path) {
//        String path = "D:\\learn\\work\\com.zhp\\question\\";
        try {
            excelData_stu(plan_id,path);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }




    //学生问卷数据excel表导出
    public void excelData_stu(int plan_Id,String Path) throws Exception{
        //开始时间
//        long begin = System.currentTimeMillis();
        Plan plan = planService.findPlanByPid(plan_Id);
        int tab_id = plan.getTab_Id();
        String tab_title = questionNaireService.findQuestionNaireByTabId(tab_id).getTab_title();
        List<UserTab> userTabs = userTabService.findTab_TId(plan_Id);
        Map<Student,List<Question>> studentListMap = new HashMap<>();
        List<Question> questions = questionService.queList3(plan_Id);//问题
        for (UserTab userTab : userTabs) {
            if (userTab.getPlan_Id()==plan_Id){
                Student student = studentService.findStudentById(userTab.getUser_Id());
                String stu_id = student.getStu_Id();
                List<Question> answers = questionService.queList4(plan_Id, stu_id);//答案
                studentListMap.put(student,answers);//student-questions
            }
        }
        int size = studentListMap.size();//获取填写的人数
        //创建一个工作簿07
        Workbook workbook = new SXSSFWorkbook();
        //创建一个工作表
        Sheet sheet = workbook.createSheet(tab_title);
        //第一行
        int count = 0;
        Row row1 = sheet.createRow(count);
        row1.createCell(count).setCellValue("序号");//(1,1)
        row1.createCell(count+1).setCellValue("学院");//(1,2)
        row1.createCell(count+2).setCellValue("专业");//(1,2)
        row1.createCell(count+3).setCellValue("年级");//(1,2)
        row1.createCell(count+4).setCellValue("班级");//(1,2)
        row1.createCell(count+5).setCellValue("姓名");//(1,2)
        row1.createCell(count+6).setCellValue("性别");//(1,2)
        for (int i = 1; i <= size; i++) {
            for (Question question : questions) {
                if (question.getNum_Id()==i) {
                    row1.createCell(count+6+i).setCellValue(question.getQue_title());
                }
            }
        }

        //写入数据
        int rowNum = 1;
        Set<Student> students = studentListMap.keySet();
        Iterator<Student> iterator = students.iterator();
        while (iterator.hasNext()) {
            Student student = iterator.next();
            Row row = sheet.createRow(rowNum);
            row.createCell(count).setCellValue(rowNum);//(1,1)
            row.createCell(count+1).setCellValue(student.getCollege());//(1,2)
            row.createCell(count+2).setCellValue(student.getMajor());//(1,2)
            row.createCell(count+3).setCellValue(student.getGrade());//(1,2)
            row.createCell(count+4).setCellValue(student.getS_class());//(1,2)
            row.createCell(count+5).setCellValue(student.getStu_name());//(1,2)
            String sex = student.getStu_sex()==1 ? "男" : "女";
            row.createCell(count+6).setCellValue(sex);//(1,2)
//            System.out.println(student);
            List<Question> que_stu = studentListMap.get(student);
            if (que_stu!=null){
                for (int i = 1; i <= size; i++) {
                    for (Question question : que_stu) {
                        if (question.getNum_Id()==i) {
                            row.createCell(count+6+i).setCellValue(question.getQue_content());
                        }
                    }
                }
            }
            rowNum++;
        }
        FileOutputStream fileOutputStream = new FileOutputStream(Path + tab_title +"调研结果(学生).xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        //清除临时文件---因为此方法会生成临时文件，所有得清除
        ((SXSSFWorkbook)workbook).dispose();
        System.out.println("over");
        //结束时间
//        long end = System.currentTimeMillis();
//        System.out.println( (double)(end-begin)/1000 );

    }

    //教职工问卷数据excel表导出
    public void excelData_tea(int plan_Id,String Path) throws Exception{
        //开始时间
//        long begin = System.currentTimeMillis();
        Plan plan = planService.findPlanByPid(plan_Id);
        int tab_id = plan.getTab_Id();
        String tab_title = questionNaireService.findQuestionNaireByTabId(tab_id).getTab_title();
        List<UserTab> userTabs = userTabService.findTab_TId(plan_Id);
        Map<Teacher,List<Question>> teacherListMap = new HashMap<>();
        List<Question> questions = questionService.queList3(plan_Id);//问题
        for (UserTab userTab : userTabs) {
            if (userTab.getPlan_Id()==plan_Id){
                Teacher teacher = teacherService.teacherListById(userTab.getUser_Id());
                String tea_id = teacher.getTea_Id();
                List<Question> answers = questionService.queList4(plan_Id, tea_id);//答案
                teacherListMap.put(teacher,answers);//student-questions
            }
        }
        int size = teacherListMap.size();//获取填写的人数
        //创建一个工作簿07
        Workbook workbook = new SXSSFWorkbook();
        //创建一个工作表
        Sheet sheet = workbook.createSheet(tab_title);
        //第一行
        int count = 0;
        Row row1 = sheet.createRow(count);
        row1.createCell(count).setCellValue("序号");//(1,1)
        row1.createCell(count+1).setCellValue("部门");//(1,2)
        row1.createCell(count+2).setCellValue("姓名");//(1,2)
        row1.createCell(count+3).setCellValue("性别");//(1,2)
        for (int i = 1; i <= size; i++) {
            for (Question question : questions) {
                if (question.getNum_Id()==i) {
                    row1.createCell(count+3+i).setCellValue(question.getQue_title());
                }
            }
        }

        //写入数据
        int rowNum = 1;
        Set<Teacher> teachers = teacherListMap.keySet();
        Iterator<Teacher> iterator = teachers.iterator();
        while (iterator.hasNext()) {
            Teacher teacher = iterator.next();
            Row row = sheet.createRow(rowNum);
            row.createCell(count).setCellValue(rowNum);//(1,1)
            row.createCell(count+1).setCellValue(teacher.getOffice());//(1,2)
            row.createCell(count+2).setCellValue(teacher.getTea_name());//(1,2)
            String sex = teacher.getTea_sex()==1 ? "男" : "女";
            row.createCell(count+3).setCellValue(sex);//(1,2)
//            System.out.println(teacher);
            List<Question> que_stu = teacherListMap.get(teacher);
            if (que_stu!=null){
                for (int i = 1; i <= size; i++) {
                    for (Question question : que_stu) {
                        if (question.getNum_Id()==i) {
                            row.createCell(count+3+i).setCellValue(question.getQue_content());
                        }
                    }
                }
            }
            rowNum++;
        }
        FileOutputStream fileOutputStream = new FileOutputStream(Path + tab_title +"调研结果(教职工).xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        //清除临时文件---因为此方法会生成临时文件，所有得清除
        ((SXSSFWorkbook)workbook).dispose();
        System.out.println("over");
        //结束时间
//        long end = System.currentTimeMillis();
//        System.out.println( (double)(end-begin)/1000 );

    }

}
